#!/usr/bin/python3
from openpyxl import load_workbook
import os, gc, json
from .Base_Plugin import Base_Plugin


class Table_Column:
    """
    表列
    """

    def __init__(
        self,
        idx,
        name,
        data_type,
        not_null,
        is_unique,
        default_value,
        description,
        single_verify,
        complex_type,
    ) -> None:
        self.idx = idx
        self.name = name
        self.data_type = data_type
        self.not_null = not_null
        self.is_unique = is_unique
        self.default_value = default_value
        self.description = description
        self.single_verify = single_verify
        self.complex_type = complex_type

    def to_dict(self):
        _dict = {
            "idx": self.idx,
            "name": self.name,
            "data_type": self.data_type,
            "not_null": self.not_null,
            "is_unique": self.is_unique,
            "default_value": self.default_value,
            "description": self.description,
            "single_verify": self.single_verify,
            "complex_type": self.complex_type,
        }
        return _dict


class Table:
    """
    表
    """

    def __init__(self, idx, name, description, module_name, create_date) -> None:
        self.idx = idx
        self.name = name
        self.description = description
        self.module_name = module_name
        self.create_date = create_date
        self.columns = list[Table_Column]()

    def to_dict(self):
        columns_dict = list()
        for column in self.columns:
            columns_dict.append(column.to_dict())
        _dict = {
            "idx": self.idx,
            "name": self.name,
            "description": self.description,
            "module_name": self.module_name,
            "create_date": self.create_date,
            "columns": columns_dict,
        }
        return _dict


class Lookup_Item:
    """
    数据字典项
    """

    def __init__(self, lookup_type, code, name_cn, name_en, additional, enable) -> None:
        self.lookup_type = lookup_type
        self.code = code
        self.name_cn = name_cn
        self.name_en = name_en
        self.additional = additional
        self.enable = enable

    def to_dict(self):
        _dict = {
            "lookup_type": self.lookup_type,
            "code": self.code,
            "name_cn": self.name_cn,
            "name_en": self.name_en,
            "additional": self.additional,
            "enable": self.enable,
        }
        return _dict


class Lookup_Type:
    """
    数据字典类
    """

    def __init__(self, code, name_cn, name_en, enable) -> None:
        self.code = code
        self.name_cn = name_cn
        self.name_en = name_en
        self.enable = enable
        self.items = list[Lookup_Item]()

    def to_dict(self):
        items_dict = list()
        for item in self.items:
            items_dict.append(item.to_dict())
        _dict = {
            "code": self.code,
            "name_cn": self.name_cn,
            "name_en": self.name_en,
            "enable": self.enable,
            "items": items_dict,
        }
        return _dict


class My_Encoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Table):
            return obj.to_dict()
        if isinstance(obj, Table_Column):
            return obj.to_dict()


class Export_Project_File_To_Json(Base_Plugin):
    """工程文件转JSON插件"""

    def __init__(self, context) -> None:
        super().__init__()
        self.context = context
        self.db = self.context["db"]

    def save_file(self, tables: list[Table], dir):
        with open(dir, "w", encoding="utf-8") as f:
            f.write(json.dumps(tables, cls=My_Encoder, indent=4, ensure_ascii=False))

    def add_columns(self, sheet, table: Table):
        for row in sheet:
            if row[0].row < self.project_config["列字段开始行"]:
                continue

            column = Table_Column(
                row[0].row - 3,
                row[1].value,
                row[2].value,
                row[3].value,
                row[4].value,
                row[5].value,
                row[6].value,
                row[7].value,
                row[8].value,
            )
            table.columns.append(column)

    def run(self, workspace, source):
        _target_path = os.path.join(workspace, source.replace("xlsx", "json"))

        workbook = load_workbook(os.path.join(workspace, source))
        _directory = workbook["目录"]

        tables = list[Table]()

        for row in _directory.rows:
            if row[0].row < self.project_config["通用开始行"]:
                continue

            table = Table(
                row[0].row - 1,
                row[1].value,
                row[2].value,
                row[3].value,
                row[4].value,
            )
            self.add_columns(workbook[row[2].value].rows, table)
            tables.append(table)

        self.save_file(tables, _target_path)

        del workbook
        gc.collect()
        return source
